package com.rjwh.dingdong.client.server;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLConnection;
import java.net.URLDecoder;

public class HttpFileRequestHandler implements HttpRequestHandler {

    private String webRoot;

    public HttpFileRequestHandler(final String webRoot) {
        this.webRoot = webRoot;
    }

    @Override
    public void handle(HttpRequest request, HttpResponse response,
                       HttpContext context) throws HttpException, IOException {
        String target = "";
        try{
            target = URLDecoder.decode(request.getRequestLine().getUri(),
                    "UTF-8");
        }catch(Exception e){}
        int indexof = target.indexOf("?");
        if(indexof>=0){
            target =  target.substring(0,indexof);
        }

        final File file = new File(this.webRoot, target);
        if (!file.exists()) { // 不存在
            response.setStatusCode(HttpStatus.SC_OK);
            StringEntity entity = new StringEntity(
                    "<html><body><h1>Error 404, file not found.</h1></body></html>",
                    "UTF-8");
            response.setHeader("Content-Type", "text/html");
            response.setEntity(entity);
        } else if (file.canRead()) { // 可读
            response.setStatusCode(HttpStatus.SC_OK);
            HttpEntity entity = null;
            if (file.isDirectory()) { // 文件夹

                File gameFile = searchGameFile(file, target);
                if (gameFile == null) {
                    entity = new StringEntity(
                            "<html><body><h1>Error 404, file not found.</h1></body></html>",
                            "UTF-8");
                    response.setHeader("Content-Type", "text/html");
                } else {
                    String contentType = URLConnection
                            .guessContentTypeFromName(gameFile.getAbsolutePath());
                    contentType = null == contentType ? "charset=UTF-8"
                            : contentType + "; charset=UTF-8";
                    entity = new FileEntity(gameFile, contentType);
                    response.setHeader("Content-Type", contentType);
                }
            } else { // 文件
                String contentType = URLConnection
                        .guessContentTypeFromName(file.getAbsolutePath());
                contentType = null == contentType ? "charset=UTF-8"
                        : contentType + "; charset=UTF-8";
                entity = new FileEntity(file, contentType);
                response.setHeader("Content-Type", contentType);
//                HttpParams par
//                response.setParams();
            }
            response.setEntity(entity);
        } else { // 不可读
            response.setStatusCode(HttpStatus.SC_OK);
            StringEntity entity = new StringEntity(
                    "<html><body><h1>Error 403, access denied.</h1></body></html>",
                    "UTF-8");
            response.setHeader("Content-Type", "text/html");
            response.setEntity(entity);
        }
    }

    /**
     * 创建文件列表浏览网页
     */
    private File searchGameFile(File dir, String target)
            throws UnsupportedEncodingException {

		/* 目录列表 */
        File[] files = dir.listFiles();
        if (null != files) {
            for (File f : files) {
                if (f.getName().equals("index.html")) {
                    return f;
                }
            }
        }
        return null;
    }


}
